/**
 * 用户相关接口
 */
const express = require('express')
const router = express.Router()
const pool = require('../../db/db')
// 引入发送邮件的模块
const nodemailer = require('nodemailer')
const { generateToken } = require('../../auth/jwt')
const Response = require('../../utils/ResponseData')


/**
 * 校验邮箱是否已经注册的接口
 * url: http://localhost:3000/user/checkEmail
 * method: post
 * params: req.body
 */
router.post('/checkEmail', (req, res, next) => {
    let { email } = req.body
    // 编写sql
    let sql = `select * from user where u_email=?`
    // 执行sql
    pool.query(sql, [email], (err, result) => {
        if (err) {
            console.log('/user/checkEmail', err)
            next(err)
            return
        }
        if (result.length == 0) {
            res.send(Response.success(null, '该邮箱可以使用！'))
        } else {
            res.send(Response.error('该邮箱已被注册！'))
        }
    })

})
/**
 * 发送邮箱验证码接口
 * url: http://localhost:3000/user/sendCode
 * method:post
 * params： email
 */
router.post('/sendCode', (req, res, next) => {
    // 生成4位数字验证码
    let code = Math.floor(Math.random() * (9999 - 1000 + 1) + 1000)
    let { email } = req.body
    // 编写sql
    let sql = `insert into user_code value(?,?)`
    // 执行sql
    pool.query(sql, [email, code], (err, result) => {
        if (err) {
            console.log('/user/sendCode', err);
            next(err)
            return
        }
        // 发送邮件
        // 需要制作一个邮件模板
        let transporter = nodemailer.createTransport({
            host: 'smtp.qq.com' || 'smtp.163.com',
            secureConnection: true,
            port: 465,
            auth: {
                user: '286693790@qq.com',  // 邮箱账号
                pass: 'vubfucdfzigvbhdf',  // 授权码
            }
        })
        // 配置相关参数
        let options = {
            from: '286693790@qq.com',  // 发送者
            to: `${email}`,  // 接收者，也就是用户的注册邮箱
            subject: '宠物家园有限责任公司',  // 邮箱标题
            html: `
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta http-equiv="X-UA-Compatible" content="IE=edge">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Document</title>
                </head>
                <body>
                    <div class="center">
                        <h3>尊敬的用户您好：</h3>
                        <p>欢迎您注册宠物家园，您的验证码是${code},请注意查收</p>
                    </div>
                </body>
                </html> 
                `
        }
        // 发送邮件
        transporter.sendMail(options, (err, msg) => {
            if (err) {
                console.log(err);
                res.send(Response.error(err))
            } else {
                res.send(Response.success(null, '验证码发送成功'))
            }
        })
    })
})

/**
 * 邮箱验证码是否正确接口
 * url: http://localhost:3000/user/checkCode
 * method: post
 * params: email、 code
 */
router.post('/checkCode', (req, res, next) => {
    // 获取前端传来的邮箱，验证码
    let { email, code } = req.body
    console.log(req.body, '===');
    let sql = `select * from user_code where u_email=? and u_code=?`
    // 执行sql
    pool.query(sql, [email, code], (err, result) => {
        if (err) {
            console.log('/user/checkCode', err)
            next(err)
            return
        }
        console.log(result);
        if (result.length == 0) {
            res.send(Response.error('验证码输入有误！'))
        } else {
            res.send(Response.success(null, '验证码输入正确！'))
        }
    })
})

/**
 * 用户注册接口
 * url： http://localhost:3000/user/register
 * method： post
 * params： uName, uEmail, uPwd
 * 
 */
router.post('/register', (req, res, next) => {
    let { uName, uEmail, uPwd } = req.body
    console.log(req.body);
    // 编写sql
    let sql = `insert into user(u_name,u_email,u_pwd) values (?,?,?)`
    // 执行sql
    pool.query(sql, [uName, uEmail, uPwd], (err, result) => {
        if (err) {
            console.log('/user/checkCode', err)
            next(err)
            return
        }
        if (result.affectedRows > 0) {
            res.send(Response.success(null, '用户注册成功！'))
        } else {
            res.send(Response.error("用户注册失败！"))
        }
    })
})
// 用户登录接口
router.post('/login', (req, res) => {
    console.log(req.body);
    let { email, password } = req.body
    let sql = `select * from user where u_email=? and u_pwd=?`
    pool.query(sql, [email, password], (err, result) => {
        if (err) {
            console.log('/user/login', err)
            next(err)
            return
        }
        if (result.length > 0) {
            let token = generateToken(result[0].u_id)

            let user = { ...result[0], u_pwd: '', token: 'Bearer ' + token }
            res.send(Response.success(user, '登录成功！'))
        } else {
            res.send(Response.error('用户名或密码错误！'))
        }
    })
})

module.exports = router